
package com.hlkj.pay.util;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author HlpayTeam
 * @date 2024/12/19 16:06
 */
public class FileUtils {

    public static byte[] fileBytes(String imageUrl) throws IOException {
        // 创建 URL 对象
        URL url = new URL(imageUrl);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        // 获取图片输入流
        try (InputStream inputStream = connection.getInputStream()) {
            // 读取图片字节数据
            byte[] imageBytes = inputStream.readAllBytes();
            // 将字节数据编码成 EasyPayBase64
            return imageBytes;
        }
    }
    /**
     * 文件上传
     *
     * @param fileUrl
     * @return
     * @throws Exception
     */
    public static void fileUpload(File dir, String fileUrl, String fileName) {
        if (!StringUtils.hasText(fileUrl)) {
            return;
        }
        // log.info("富友上传文件 url:{}, fileName:{}",fileUrl,fileName);
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        try {
            URL url = new URL(fileUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // File file = new File(connection.getInputStream());
            // 创建临时文件
            // 将输入流复制到临时文件中
            outputStream = new FileOutputStream(dir.getPath() + File.separator + fileName + ".jpg");
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = connection.getInputStream().read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                }
                catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    public static void zipFolder(Path folderToZip, Path zipFilePath) throws IOException {
        try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(zipFilePath))) {
            Files.walkFileTree(folderToZip, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Path targetFile = folderToZip.relativize(file);
                    zipOut.putNextEntry(new ZipEntry(targetFile.toString()));
                    Files.copy(file, zipOut);
                    zipOut.closeEntry();
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    Path targetDir = folderToZip.relativize(dir);
                    zipOut.putNextEntry(new ZipEntry(targetDir.toString() + "/"));
                    zipOut.closeEntry();
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }
    // 下载并打包多个图片文件成 ZIP
    private static void zipImages(List<String> imageUrls, String zipFilePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            // 遍历所有图片 URL
            for (String imageUrl : imageUrls) {
                // 下载每张图片并获取图片文件名
                File imageFile = downloadImage(imageUrl);
                if (imageFile != null) {
                    // 将图片添加到 ZIP 文件中
                    addImageToZip(imageFile, zos);
                    // 删除临时图片文件
                    imageFile.delete();
                }
            }
        }
    }

    // 下载远程图片并保存为临时文件
    private static File downloadImage(String imageUrl) {
        File tempFile = null;
        try (InputStream inputStream = new URL(imageUrl).openStream()) {
            // 获取图片文件名
            String imageName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
            // 创建临时文件来保存图片
            tempFile = new File(imageName);
            try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tempFile;
    }

    // 将图片文件添加到 ZIP 文件中
    private static void addImageToZip(File imageFile, ZipOutputStream zos) throws IOException {
        try (FileInputStream fis = new FileInputStream(imageFile)) {
            // 创建一个新的 ZipEntry 条目
            ZipEntry zipEntry = new ZipEntry(imageFile.getName());
            zos.putNextEntry(zipEntry);
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, bytesRead);
            }
            zos.closeEntry();
        }
    }
}
